//轮播图
import Api from './service/Api';
import { login_way, serverLogin } from './common/Function';
import { loadNewsDetail, loadNewsList } from './pages/news';
import { loadModuleDetail, loadModuleList } from './pages/module';
import { bannerPage } from './pages/banner';
import { changeAccountPage } from './pages/changeAccount';
import './pages/none';
import JsBridge from './service/JsBridge';
export function leftHomePage () {
  const userInfo = JSON.parse(localStorage.getItem('yxtUser'));

  // 改变请求地址
  const qarr = window.location.search.slice(1).split('&');
  for (let i = 0; i < qarr.length; i++) {
    const a = qarr[i].split("=");
    if (a[0] === 'burl') {
      API.baseUrl = a[1];
      break;
    }
  }

  if (userInfo) {

      let list1 = $.Deferred(); // 新闻列表
      let list2 = $.Deferred(); // 模块列表

      Api.get("/EduPlate/MSGAppIndex/InterfaceJson.asmx/List_GetList", {
          Page: 1,
          PageSize: 6,
          Unit_ID: userInfo.Unit_ID
      }).then((resp) => {
          console.log(resp);
          if (resp && resp.Goodo && resp.Goodo.R) {
              const records = resp.Goodo.R;
              list1.resolve(records);

          } else if (resp.Goodo.EID == '0'){ // 请求成功却没有数据
            list1.resolve([]);
          } else {
            list1.resolve(false);
          }
      });

      Api.get('/EduPlate/MSGAppIndex/InterfaceJson.asmx/Module_GetList')
      .then((resp) => {
        console.log(resp);

        if (resp && resp.Goodo && resp.Goodo.R) {
            const records = resp.Goodo.R;
            list2.resolve(records);
        } else if (resp.Goodo.EID == '0'){ // 请求成功却没有数据
          list2.resolve([]);
        } else {
          list2.resolve(false);
        }
      });

      $.when(list1, list2).done(function (v1, v2) {
        const baseUrl = API.baseUrl;
        if ((v1 && v1.length < 1) && (v2 && v2.length < 1)) { // 都请求成功但无数据

          const tpl = `
          <div class="top">
              <p>首页</p>
              <a id="change_acc" herf="javascript:void(0);">切换单位</a>
          </div>
          <div style="
          height: 880px;
          line-height: 880px;
          text-align: center;
          font-size: 30px;
          color: #666;">
            管理员尚未设置首页
          </div>
          <div class="footer">
              <img src="img/public/footer.png" />
              <a href="#" class="ent">${userInfo.UserName}</a>
              <a href="news_index.html?burl=${API.baseUrl}">进入系统</a>
          </div>
          `

          $('.left').html(tpl);

        } else {
          const tpl = `
          <div class="top">
              <p>首页</p>
              <a id="change_acc" herf="javascript:void(0);">切换单位</a>
          </div>
          <div class="slider" id="banner">
          <ul style="left:0;">

          </ul>
          <div class="btn">
              <a href="javascript:;" class="btn_left"></a>
              <a href="javascript:;" class="btn_right"></a>
              <ul>
                  <li class="on"></li>

              </ul>
          </div>
          </div>
          <div class="nav">
              <ul>
              ${
                v2.map(item => {
                return `
                  <li><a class="module_btn" data-data='${JSON.stringify(item)}'><img src="${Api.imageUrl(item.PicUrl)}"/><span>${item.Title}</span></a></li>
                `
              }).join('')
              }
              </ul>
          </div>
          <div class="news">
              <h1>最新新闻</h1>
              <a id="news_more" class="morn"><img src="img/news_public/news_sys_alone.png"/>更多</a>
              <ul>
              ${v1.map(item => {

                        return `<li class="hot_news"><a class="news_detail" data-id="${item.Contents_ID}">
                            <span class="flag">最新</span>
                            <p>${item.ContentTitle}</p>
                            <span>${moment(item.SubmitDate, 'YYYY-MM-DD HH:mm:ss').format('M-DD')}</span>
                        </a></li>`;


                  }).join('') + "</ul>"}
              </ul>
          </div>
          <div class="footer">
              <img src="img/public/footer.png" />
              <a href="#" class="ent">${userInfo.UserName}</a>
              <a href="news_index.html?burl=${API.baseUrl}">进入系统</a>
          </div>
          `

          $('.left').html(tpl);
          var fn=setInterval(function(){	//循环执行函数
				Api.get('/BasePlate/Interface/IInterfaceJson.asmx/CheckOnline2', {
				    SessionID: userInfo.SessionID,
				    State:2
				}).then(function(resp) {
				       console.log(resp);
				       console.log('登录方式')
				       if(resp.IsOnline==0){
				       	console.log('$c11111111111')
				       	JsBridge.sendRequest("custom.get", {key: 'yxtLog'}).then(jsrep => {
				            const fistLog = JSON.parse(jsrep.data.value);
				            const user = fistLog.logs[0].user;
				            const pass = fistLog.logs[0].pass;
				            const UnitUrl = fistLog.logs[0].UnitUrl;
				            const UnitUrl2 = fistLog.logs[0].UnitUrl2;
				//          console.log(user)
				//          console.log(pass)
				//          console.log(5555555555555555555)
				//          //				alert('有掉线')
				//          console.log(UnitUrl)
				//
													JsBridge.sendRequest("user.password", {password: pass}).then(resp => {
										      $.ajax({
										        url: API.baseUrl + '/BasePlate/Interface/IInterfaceJson.asmx/LoginUser',
										        type: "post",
										        dataType: "json",
										        data: {
										          LoginID: user,
										          EncyptPassword: resp.data.password,
										          OnlineType: 130,
										          DeviceName: 'web test',
										          Place: 'cs'
										        },
										        success: function (json) {
				
										          layer.closeAll();
				//						          alert(111);
										          JsBridge.sendRequest("custom.get", {key: 'yxtLog'}).then(jsrep => {
				//						              alert(JSON.stringify(jsrep));
										              let cookie_log = jsrep.data.value;
										              let logs = [];
										              if (cookie_log) {
										                logs = JSON.parse(cookie_log).logs;
										              }
				
										              if (json.Goodo.UserName) {
										                $(".login").unbind("click");
										                //Cookies.set("yxtUser", json.Goodo);
				
										                JsBridge.sendRequest('user.login', { userInfo: json.Goodo, LoginID: user, EncyptPassword: resp.data.password, UnitUrl: API.baseUrl,UnitUrl2: UnitUrl2 , UnitName: json.Goodo.UnitName });
				
										                localStorage.setItem("yxtUser", JSON.stringify(json.Goodo));
										                // 找出同单位同姓名的记录并删除
										                let { Unit_ID, UnitName, UserName, User_ID } = json.Goodo;
										                let repeatIndex;
										                for (let i = 0; i < logs.length; i++) {
										                  if (logs[i].Unit_ID === Unit_ID && logs[i].User_ID === User_ID) {
										                    repeatIndex = i;
										                    break;
										                  }
										                }
										                repeatIndex >= 0 && logs.splice(repeatIndex, 1); // 去重
										                logs.unshift({ Unit_ID, UnitName, UserName, User_ID, UnitUrl: API.baseUrl,UnitUrl2, user, pass }); // 添加新记录
										                JsBridge.sendRequest("custom.set", {key: 'yxtLog', value: JSON.stringify({ "logs": logs })}) // 添加到本地
				
										                location.href = `index.html?burl=${UnitUrl}`; // 跳转到首页
				//														ChatManager.refreshUser();
				
										              } else {
				//						              	alert('重登录出错')
										                layer.msg(`${json.Goodo.ErrorMessage}`);
										              }
										          	});
										        },
										        error: function (err) {
										          layer.closeAll();
										          layer.msg('网络请求超时出错');
										          // console.log(err);
										        }
										      });
				          })
				        })
				       }//if完
				});
			},10000)
            
          banner();
          $('.news').find('.flag').eq(0).css('display','inline-block');
          $('.news').find('.flag').eq(1).css('display','inline-block');
          $('.news').find('.flag').eq(2).css('display','inline-block');
          // 新闻更多按钮事件
          $('#news_more').click(function() {
              loadNewsList(1);
              return false;
          });
          // 新闻详情
          $('.news_detail').click(function() {
              let btn = $(this);
              if (btn.hasClass('active')) {
                return false;
              } else {
                $('a.news_detail').removeClass('active');
                btn.addClass('active');
                loadNewsDetail(btn.data('id'));
                $('a.module_btn').removeClass('active');
              }

              return false;
          });
          // 模块按钮
          $('.module_btn').click(function() {
              let btn = $(this);
              let data = btn.data('data');
              if (btn.hasClass('active')) {
                return false;
              } else {
                btn.addClass('active');
                loadModuleList({id: data.Subjects_ID, url: data.ModuleUrl, title: data.Title, pageNo: 1});
                btn.parent().siblings().children('.module_btn').removeClass('active');
                $('a.news_detail').removeClass('active');
              }

              return false;
          });


        }

        // 更换单位按钮事件
        $('#change_acc').click(function() {
            changeAccountPage();
            return false;
        });

        $(window).trigger("resize");

      });

  }
}

function banner() {
    var $Unit_ID = 6280;
    var $sum = 6;
   
    $.ajax({
        url: API.baseUrl + '/EduPlate/MSGAppIndex/InterfaceJson.asmx/Pic_GetXD',
        type: "get",
        dataType: "json",
        data: {
            Unit_ID: $Unit_ID,
            nTop: $sum

        },
        success: function (json) {
            console.log(json)
            //          	console.log(json.Goodo.R[0].Title)
            //          	console.log(json.Goodo.R[0].PicUrl)
            if (!(json.Goodo.R instanceof Array)) {
              json.Goodo.R = [json.Goodo.R, json.Goodo.R];
            }
            var $number = json.Goodo.R.length;
            //          	console.log($number)
            var numb = $number;   //按键数目
            var slider = document.getElementById("banner");
            var ul = slider.children[0];
            var btn = slider.children[1].children;
            var btn_ul = btn[2];
            var btn_li = btn[2].children;
            var num = 0;
            var x = 0;
            var test = null;
            var bool = true;
            for (var i = 0; i < numb; i++) { //添加li
                ul.innerHTML += '<li > <img src="' + Api.imageUrl(json.Goodo.R[i].PicUrl) + '"/><p></p><span>' + json.Goodo.R[i].Title + '</span></li>';
            }
            console.log(ul)
            for (var i = 0; i < numb - 1; i++) {                      ////添加按钮
                btn_ul.innerHTML += '<li>' + (i + 1) + '</li>';
            }
            ul.innerHTML = ul.innerHTML + ul.innerHTML;
            for (var i = 0; i < ul.children.length; i++) {
                //					ul.children[i].index=i;
                if (i < numb) {
                    ul.children[i].index = json.Goodo.R[i].ID;
                } else {
                    ul.children[i].index = json.Goodo.R[i - numb].ID;
                }
                ul.children[i].onclick = function () {
                    console.log(this.index);
                    var a = this.index;
                    bannerPage(a);
                    // window.location.href = 'banner.html?$Unit_ID=' + a;
                };
            }

            btn[0].onclick = function () {
                if (bool) { move(++num) }
                bool = false;

            }

            btn[1].onclick = function () {
                if (bool) {
                    if (x == 0) { ul.style.left = -(x = numb * 100) + "%"; num = numb }
                    move(--num);
                }
                bool = false;
            }


            function move(val) {
                clearInterval(test);

                var a = parseInt(ul.style.left);
                test = setInterval(function () {
                    if (a > -val * 100) { ul.style.left = -(x=x+5) + "%"; }
                    if (a < -val * 100) { ul.style.left = -(x=x-5) + "%"; }
                    //								console.log(val*100);
                    if (x == val * 100) { bool = true; clearInterval(test) }
                    if (x == 100 * (2 * numb - 1)) { ul.style.left = -(x = 100) + "%"; num = 1 }
                }, 25)

                for (var i = 0; i < btn_li.length; i++) {
                    btn_li[i].className = ""
                }
                console.log(btn_li[val % (numb)])
                // btn_li[val % (numb)].className = "on";

            }

            for (var i = 0; i < btn_li.length; i++) {
                btn_li[i].onclick = function () {
                    num = Number(this.innerHTML);
                    move(num);
                }
            }

            var paly = setInterval(function () {
                move(++num);
            }, 3000);

            slider.onmouseover = function () {
                clearInterval(paly)
            }

            slider.onmouseout = function () {
                paly = setInterval(function () {
                    move(++num);
                }, 3000);
            }

        }
    });

}





leftHomePage();
